import sched, time
from HTMLTestRunner.HTMLTestRunner import HTMLTestRunner
import pyunittest
import os
from email.utils import formataddr
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.header import Header

tests = pyunittest.defaultTestLoader.discover(os.getcwd(), pattern="Test*.py")

runner = HTMLTestRunner(
    title="这是登陆测试报告",
    description="登陆成功，密码失败，用户名失败",
    verbosity=2,
    stream=open(file="测试报告.html", mode="w+", encoding="utf-8")
)

s = sched.scheduler(time.time, time.sleep)

# 邮件配置信息
sender_email = 'wyguolai@163.com'  # 发件人邮箱地址
sender_password = 'ARUYHGWGTBPBAQEC'  # 发件人邮箱密码或授权码
receiver_emails = ['qaz242@foxmail.com']  # 接收人邮箱地址列表
subject = '这是一份测试报告，请查收！'  # 邮件主题
html_file_path = '测试报告.html'  # HTML 文件的路径

# 创建邮件对象
msg = MIMEMultipart()
msg['Subject'] = Header(subject, 'utf-8')  # 设置主题，并指定字符编码
msg['From'] = formataddr((str(Header('随便', 'utf-8')), sender_email))  # 设置发件人名称，并指定字符编码
msg['To'] = Header(', '.join(receiver_emails), 'utf-8')  # 设置收件人名称，并指定字符编码

# 读取附件文件
attachment_file_path = '测试报告.html'  # 附件文件的路径
attachment_filename = '测试报告.html'  # 附件文件的名称


def timed_operation(sc):
    runner.run(tests)

    # 读取 HTML 文件内容
    with open(html_file_path, 'r', encoding='utf-8') as file:
        html_content = file.read()

    # 创建 HTML 正文
    html_part = MIMEText(html_content, 'html')
    msg.attach(html_part)

    with open(attachment_file_path, 'rb') as file:
        attachment = MIMEBase('application', 'octet-stream')
        attachment.set_payload(file.read())
        encoders.encode_base64(attachment)
        encoded_filename = Header(attachment_filename, 'utf-8').encode()
        attachment.add_header('Content-Disposition', f'attachment; filename="{encoded_filename}"')
        msg.attach(attachment)

    # 发送邮件
    try:
        with smtplib.SMTP_SSL('smtp.163.com', 465) as server:
            server.login(sender_email, sender_password)
            server.sendmail(sender_email, receiver_emails, msg.as_string())
        print('邮件发送成功！')
    except Exception as e:
        print('邮件发送失败:', e)

    # 安排下一次运行
    s.enter(86400, 1, timed_operation, (sc,))


# 设置一天运行一次
s.enter(86400, 1, timed_operation, (s,))
s.run()
